import json
import os
import sys
from pathlib import Path

# Ensure project root is in sys.path so that `flow_engine` can be imported without installation
proj_root = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(proj_root))

from flow_engine.core.graph import FlowGraph
from flow_engine.execution.runner import FlowRunner


def main():
    example_path = proj_root / "examples" / "http_flow.json"
    print(f"[INFO] Python={sys.version}")
    print(f"[INFO] sys.path[0]={sys.path[0]}")
    print(f"[INFO] Loading example: {example_path}")
    with open(example_path, "r", encoding="utf-8") as f:
        flow_def = json.load(f)

    graph = FlowGraph(flow_def)
    runner = FlowRunner(graph, max_steps=1000)
    print("[INFO] Running flow with empty context {}")
    result = runner.run(context={})

    trace = result.get("trace", [])
    print(f"[RESULT] trace_len={len(trace)}")
    print("[TRACE] last 5 entries:")
    for line in trace[-5:]:
        print("  ", line)

    ctx = result.get("context", {})
    print(f"[RESULT] context keys: {list(ctx.keys())}")
    nodes = ctx.get("nodes", {})
    print(f"[RESULT] nodes_len={len(nodes)}")
    if nodes:
        first_key = next(iter(nodes.keys()))
        print("[RESULT] sample node record:")
        print("  ", nodes[first_key])

    # Try optional Redis read if available and enabled
    try:
        from api.managers.redis_manager import REDIS_MANAGER
        from api.config.redis_config import get_redis_settings
        settings = get_redis_settings()
        if settings.enabled:
            print("[INFO] REDIS_ENABLED=true, attempting to read run_id context key (if any)")
            print("[WARN] No run_id generated in this script. Use service-layer run to persist #{run_id}_context.")
        else:
            print("[INFO] REDIS_ENABLED=false, skipping Redis verification.")
    except Exception as ex:
        print(f"[INFO] Redis client not available or import failed: {ex}")


if __name__ == "__main__":
    main()